package com.ice.delay.task.sample.web;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ice.delay.task.sample.dto.DelayTaskDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wangwei
 * @Date 2022/6/8 22:15
 */
@Slf4j
@RestController
public class DelayTaskController {


    public static String url = "http://localhost:8019/asynctask/task/createDelayTask";


    @GetMapping("/pushDelayTask")
    public void pushDelayTask() {
        DelayTaskDetail delayTaskDetail = new DelayTaskDetail();
        delayTaskDetail.setModuleCode("delay_task_test");
        delayTaskDetail.setTaskNotifyUrl("http://localhost:8089/delay-task-sample/delayTaskCallback");
        delayTaskDetail.setTaskCode(RandomUtil.randomString(System.currentTimeMillis() + "", 10));
        delayTaskDetail.setDelayTime(20);
        delayTaskDetail.setTaskName("延迟任务测试");
        delayTaskDetail.setImmediatelyExecute(false);
        delayTaskDetail.setRequestMethod("POST");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "ice");
        jsonObject.put("age", "18");
        delayTaskDetail.setRequestParam(jsonObject.toJSONString());
        System.out.println(JSON.toJSONString(delayTaskDetail));
        HttpResponse execute = HttpUtil.createPost(url).body(JSON.toJSONString(delayTaskDetail)).execute();
        if (execute.isOk()) {
            String body = execute.body();
            System.out.println(body);
        } else {
            System.out.println(execute.body());
        }
    }

    /**
     * 延迟任务回调
     * @Author wangwei
     * @Date 2022/6/8
     */
    @PostMapping("/delayTaskCallback")
    public JSONObject delayTaskCallback(@RequestBody JSONObject jsonObject) {
        log.info("延迟任务回调:{}", jsonObject.toJSONString());
        JSONObject object = new JSONObject();
        object.put("errorCode", "0");
        object.put("errorMsg", "成功");
        return object;
    }
}
